import utils from "../common/util.js"
import store from '@/store/index.js'

export default {	
	
	// 获取所有的消息列表
	getMessageList(){
		return new Promise((resolve, reject) => {
			uni.getStorage({
			    key: 'messageList',
			    success: function (storageMsgList) {
			        // 先找本地
			        if(storageMsgList === null || storageMsgList === undefined || storageMsgList === ""){
			        	resolve({})
			        	// uni.request({
			        	// 	url: utils.basicUrl + "/chat/single/msg/list/AllUnread",
			        	// 	method: "GET",
			        	// 	data: {
			        	// 		userId: uni.getStorageSync("userInfo").id
			        	// 	},
			        	// 	header:{
			        	// 		"satoken": uni.getStorageSync("userInfo").tokenValue
			        	// 	},
			        	// 	success: function(res) {
			        	// 		if (res.data.code === 20000) {
			        	// 			// 持久化到本地
			        	// 			uni.setStorage({
			        	// 			    key: 'messageList',
			        	// 			    data: storageMsgList,
			        	// 			    success: function () {
			        	// 			       // 通知更新消息
			        	// 			       resolve(res.data.data)
			        	// 			    }
			        	// 			});
			        	// 		} else {
			        	// 			utils.requestFail(res)
			        	// 		}
			        	// 	},
			        	// 	fail: () => {
			        	// 		uni.showModal({
			        	// 			content: "网络错误！",
			        	// 			showCancel: false
			        	// 		});
			        	// 	},
			        	// 	complete() {
			        	// 		// uni.stopPullDownRefresh()
			        	// 	}
			        	// })
			        }else {
			        	resolve(storageMsgList.data)
			        }
			    }
			});
			
			
		})
		
	},
	
	// 获取与当前好友的消息列表
	getMessageByFriend(friendId,length){
		return new Promise((resolve, reject) => {
			// 先找本地
			var storageMsgList = uni.getStorageSync("messageList")
			if(storageMsgList === null || storageMsgList === undefined || storageMsgList === ""){
				storageMsgList = {}
			}
			
			if(storageMsgList[friendId] === null || storageMsgList[friendId] === undefined || storageMsgList[friendId] === ""){
				// 查数据库
				uni.request({
					url: utils.basicUrl + "/chat/single/msg/list",
					method: "POST",
					data: {
						sender: friendId,
						receiver: uni.getStorageSync("userInfo").id
					},
					header:{
						"satoken": uni.getStorageSync("userInfo").tokenValue
					},
					success: function(res) {
						if (res.data.code === 20000) {
							// 持久化到本地
							if(res.data.data["read"].length === 0 && res.data.data["unread"].length === 0){
								storageMsgList = {}
							}else {
								storageMsgList[friendId] = res.data.data
							}
							
							uni.setStorage({
							    key: 'messageList',
							    data: storageMsgList,
							    success: function () {
							       // 通知更新消息
								   var resultMsg = res.data.data.read.concat(res.data.data.unread)
								   var start = resultMsg.length - 10 < 0 ? 0 : resultMsg.length - 10
								   var end = length
							       resolve(resultMsg.slice(start,end))
							    }
							});
						} else {
							utils.requestFail(res)
						}
					},
					fail: () => {
						uni.showModal({
							content: "网络错误！",
							showCancel: false
						});
					},
					complete() {
						// uni.stopPullDownRefresh()
					}
				})
			}else {
				// 未读消息全部转正
				var labels = []
				if(storageMsgList[friendId]["unread"] !== null && storageMsgList[friendId]["unread"] !== undefined && storageMsgList[friendId]["unread"].length > 0){
					storageMsgList[friendId]["unread"].forEach(item => {
						// item.status = 3
						labels.push(item.label)
					})
					store.commit("reduceUnReadNum",storageMsgList[friendId]["unread"].length)
				}
				
				var readMsg = storageMsgList[friendId]["read"].concat(storageMsgList[friendId]["unread"])
				storageMsgList[friendId]["read"] = readMsg
				storageMsgList[friendId]["unread"] = []
				const self = this
				uni.setStorage({
				    key: 'messageList',
				    data: storageMsgList,
				    success: function () {
				        // 通知发送方已读消息
				        // self.setMessageStatus(friendId,3,labels)
						var start = readMsg.length - length  - 10 < 0 ? 0 : readMsg.length - length - 10
						var end = readMsg.length - length 
				        resolve(readMsg.slice(start,end))
				    }
				});
			}
			
		})
	},
	
	// 更新与某好友的聊天记录状态
	setMessageStatus(friendId,status,lables){
		uni.request({
			url: utils.basicUrl + "/chat/single/msg/status",
			method: "PUT",
			data: {
				friendId: friendId,
				userId: uni.getStorageSync("userInfo").id,
				status: status,
				labels: lables
			},
			header:{
				"satoken": uni.getStorageSync("userInfo").tokenValue
			},
			success: function(res) {
				if (res.data.code === 20000) {
					console.log("通知成功")
				} else {
					utils.requestFail(res)
				}
			},
			fail: () => {
				uni.showModal({
					content: "网络错误！",
					showCancel: false
				});
			},
			complete() {
				// uni.stopPullDownRefresh()
			}
		})
	},
	
	// 发送消息
	sendMessage(message){
		return new Promise((resolve, reject) => {
			uni.request({
				url: utils.basicUrl + "/chat/single/send",
				method: "POST",
				data: {
					...message
				},
				header:{
					"satoken": uni.getStorageSync("userInfo").tokenValue
				},
				success: function(res) {
					if (res.data.code === 20000) {
						resolve(res.data.data)
					} else {
						utils.requestFail(res)
					}
				},
				fail: () => {
					uni.showModal({
						content: "网络错误！",
						showCancel: false
					});
				},
				complete() {
					// uni.stopPullDownRefresh()
				}
			})
		})
	}
	
}